package cn.jantd.modules.system.controller;


import cn.jantd.core.annotation.AutoLog;
import cn.jantd.core.annotation.PermissionData;
import cn.jantd.core.api.vo.Result;
import cn.jantd.core.poi.def.NormalExcelConstants;
import cn.jantd.core.poi.excel.ExcelImportUtil;
import cn.jantd.core.poi.excel.entity.ExportParams;
import cn.jantd.core.poi.excel.entity.ImportParams;
import cn.jantd.core.poi.view.JantdEntityExcelViewBase;
import cn.jantd.core.system.query.QueryGenerator;
import cn.jantd.core.system.vo.LoginUser;
import cn.jantd.core.util.oConvertUtils;
import cn.jantd.modules.system.entity.SerServer;
import cn.jantd.modules.system.entity.SerVirtual;
import cn.jantd.modules.system.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 虚拟机服务表 前端控制器
 * </p>
 *
 * @Author xiagf
 * @date 2019-07-04
 */
@RestController
@RequestMapping("/sys/myvirtual")
@Slf4j
public class SerMyVirtualController {
    @Autowired
    private ISerMyVirtualService serMyVirtualService;
    @Autowired
    private ISerServerService serServerService;
    /**
     * 分页列表查询
     *
     * @param virtual
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "虚拟机服务管理-分页列表查询")
    @ApiOperation(value = "虚拟机服务管理-分页列表查询")
    @PermissionData(pageComponent = "server/VirtuaList")
    @GetMapping(value = "/list")
    public Result<IPage<SerVirtual>> queryPageList(SerVirtual virtual,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<IPage<SerVirtual>> result = new Result<IPage<SerVirtual>>();
        QueryWrapper<SerVirtual> queryWrapper = QueryGenerator.initQueryWrapper(virtual, req.getParameterMap());
        Page<SerVirtual> page = new Page<SerVirtual>(pageNo, pageSize);
        IPage<SerVirtual> pageList = serMyVirtualService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }
    /**
     * 添加
     *
     * @param virtual
     * @return
     */
    @AutoLog(value = "虚拟机服务管理-添加")
    @ApiOperation(value = "虚拟机服务管理-添加")
    @PostMapping(value = "/add")
    public Result<SerVirtual> add(@RequestBody SerVirtual virtual) {
        Result<SerVirtual> result = new Result<SerVirtual>();
        try {
            virtual.setCreateTime(new Date());
            serMyVirtualService.save(virtual);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "虚拟机服务管理-编辑")
    @ApiOperation(value = "虚拟机服务管理-编辑")
    @PutMapping(value = "/edit")
    public Result<SerVirtual> edit(@RequestBody JSONObject jsonObject) {
        Result<SerVirtual> result = new Result<SerVirtual>();
        SerVirtual virtual = serMyVirtualService.getById(jsonObject.getString("id"));
        if (virtual == null) {
            result.error500("未找到对应实体");
        } else {
            SerVirtual myvirtual= JSON.parseObject(jsonObject.toJSONString(), SerVirtual.class);
            myvirtual.setUpdateTime(new Date());
            boolean ok = serMyVirtualService.updateById(myvirtual);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "虚拟机服务管理-通过id删除")
    @ApiOperation(value = "虚拟机服务管理-通过id删除")
    @CacheEvict(value = "loginUser_cacheRules", allEntries = true)
    @DeleteMapping(value = "/delete")
    public Result<SerVirtual> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SerVirtual> result = new Result<SerVirtual>();
        SerVirtual virtual = serMyVirtualService.getById(id);
        if (virtual == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = serMyVirtualService.removeById(id);
          QueryWrapper<SerServer> queryWrapper=new QueryWrapper<>();
          queryWrapper.eq("virtualserve",virtual.getVirtualName());
          serServerService.remove(queryWrapper);
            if (ok) {
                result.success("删除成功!");
            }
        }

        return result;
    }



    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "服务管理-通过id查询")
    @ApiOperation(value = "服务管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SerVirtual> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SerVirtual> result = new Result<SerVirtual>();
        SerVirtual sysspecialty = serMyVirtualService.getById(id);
        if (sysspecialty == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysspecialty);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 查询全部专业类别
     *
     * @return
     */
    @GetMapping(value = "/virtuall")
    public Result<List<SerVirtual>> specialtyall() {
        Result<List<SerVirtual>> result = new Result<>();
        List<SerVirtual> list = serMyVirtualService.list();
        if (list.isEmpty()) {
            result.error500("未找到专业类别信息");
        } else {
            result.setResult(list);
            result.setSuccess(true);
        }
        return result;
    }



    /**
     * 导出excel
     *
     * @param serVirtual
     * @param request
     * @return
     */
    @AutoLog(value = "服务管理-导出excel")
    @ApiOperation(value = "服务管理-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(SerVirtual serVirtual, HttpServletRequest request) {
        // Step.1 组装查询条件
        QueryWrapper<SerVirtual> queryWrapper = QueryGenerator.initQueryWrapper(serVirtual, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JantdEntityExcelViewBase());
        List<SerVirtual> pageList = serMyVirtualService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "服务列表");
        mv.addObject(NormalExcelConstants.CLASS, SerVirtual.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("服务列表数据", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "服务管理-通过excel导入数据")
    @ApiOperation(value = "服务管理-通过excel导入数据")
    @PostMapping(value = "/importExcel")
    public Result<Object> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SerVirtual> listSerVirtual = ExcelImportUtil.importExcel(file.getInputStream(), SerVirtual.class, params);
                for (SerVirtual serVirtualExcel : listSerVirtual) {
                    serMyVirtualService.save(serVirtualExcel);
                }
                return Result.ok("文件导入成功！数据行数：" + listSerVirtual.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return Result.error("文件导入失败！");
    }

}
